<template>
  <div style="overflow: hidden; width: 100%; height: 100%">
    <VxeBasicTable ref="tableRef" v-bind="gridOptions">
      <template #toolbar_buttons>
        <a-button type="primary" @click="handleCreate"> 新增费用明细 </a-button>
        <ImpExcel @success="excelSuccessFn" dateFormat="YYYY-MM-DD">
          <a-button class="m-3" :loading="loading"> 导入Excel </a-button>
        </ImpExcel>

        <a-button @click="aoaToExcel"> 模版下载 </a-button>
        <div style="margin-left: 10px">
          <span style="font-size: 15px">匹配MS采购单的条件有哪些</span>
          <Tooltip placement="top">
            <template #title>
              <span
                >供应商+MS采购单物料编号+开始日期+结束日期(非必填)+退款条件类型+退款条件数量/金额</span
              >
            </template>
            <InfoCircleOutlined
              style="font-size: 19px; color: #cc8500; cursor: pointer; margin-left: 5px"
            />
          </Tooltip>
        </div>
      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>

      <template #isReturn_default="{ row }">
        <div style="cursor: pointer">
          <div v-if="!row.isReturn">否</div>
          <div v-if="row.isReturn == 1" style="color: green" @click="openUserModal(row)"
            >是(点击查看符合单据)</div
          >
        </div>
      </template>
    </VxeBasicTable>

    <FormModal @register="register" @success="handleSuccess" />
    <OrderListModal @register="orderModal[0]" />

    <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
      <p v-for="(item, index) in msgList">第{{ item.index }}行 {{ item.message }}</p>
    </Modal>
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import {
    mouldListApi,
    closeMouldApi,
    deleteMouldApi,
    importMsOrderExcelApi,
    priceTableListApi,
  } from '@/api/sys/msUser';
  import { aoaToSheetXlsx, ImpExcel } from '@/components/Excel';
  import {
    BasicTableProps,
    VxeBasicTable,
    VxeGridInstance,
    VxeGridListeners,
  } from '@/components/VxeTable';
  import {
    columns,
    searchFormSchema,
    vxeTableColumns,
    vxeTableFormSchema,
    openIsReturn,
  } from './role.data';
  import { InfoCircleOutlined } from '@ant-design/icons-vue';

  import { reactive, ref } from 'vue';
  import { useUserStore } from '@/store/modules/user';

  import FormModal from './FormModal.vue';
  import OrderListModal from '../../priceList/OrderListModal.vue';
  import { useMessage } from '@/hooks/web/useMessage';
  import { useModal } from '@/components/Modal';
  import { Modal, Tooltip } from 'ant-design-vue';

  defineOptions({ name: 'MouldList' });
  const { createMessage } = useMessage();
  const userStore = useUserStore();

  const [register, { openModal, closeModal }] = useModal();
  const orderModal = useModal();
  const loading = ref(false);
  const visible = ref(false);
  const msgList = ref([]);

  const tableRef = ref<VxeGridInstance>();

  const gridOptions = reactive<BasicTableProps>({
    id: 'VxeTable',
    keepSource: true,
    editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
    showOverflow: true,
    size: 'mini',
    height: 'auto',
    columns: vxeTableColumns,
    toolbarConfig: {
      slots: {
        buttons: 'toolbar_buttons',
      },
    },
    formConfig: {
      enabled: true,
      items: vxeTableFormSchema,
    },
    pagerConfig: {
      pageSize: 20,
    },
    proxyConfig: {
      props: {
        result: 'data.list',
        list: 'data.list',
        total: 'data.totalResult',
        message: 'message',
      },
      ajax: {
        query: async ({ page, form, order }) => {
          return mouldListApi({
            page: page.currentPage,
            pageSize: page.pageSize,
            IfXuNiJian: 1,
            ...form,
            order,
          });
        },
        // queryAll: async ({ form }) => {
        //   return await demoListApi(form);
        // },
      },
    },
  });

  const gridEvents: VxeGridListeners = {
    sortChange({ field, order }) {
      console.log(field, order);
    },
  };

  function getActions(record) {
    let arr = [];
    let userName = userStore.getUserInfo?.userName;
    if ((record.isClose != 1 && userName == record.userName) || userName == record.createUserName) {
      arr.push({
        // icon: 'clarity:note-edit-line',
        label: '编辑',
        onClick: handleEdit.bind(null, record),
      });
      arr.push({
        // icon: 'ant-design:delete-outlined',
        label: '关闭',
        color: 'error',
        popConfirm: {
          title: '是否确认关闭该费用？',
          placement: 'left',
          confirm: handleClose.bind(null, record),
        },
      });
    }
    if (userName == 'manage') {
      // arr.push(
      //   {
      //     // icon: 'ant-design:delete-outlined',
      //     label:'删除',
      //     color: 'error',
      //     popConfirm: {
      //       title: '是否确认删除？',
      //       placement: 'left',
      //       confirm: handleDelete.bind(null, record),
      //     },
      //   })
    }

    return arr;
  }

  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  function handleDelete(record: Recordable) {
    //console.log(record);

    deleteMouldApi(record)
      .then((res) => {
        createMessage.success(res.message);
      })
      .catch((res) => {
        createMessage.error(res.message);
      })
      .finally(() => {
        tableRef.value.commitProxy('reload');
      });
  }

  function handleClose(record: Recordable) {
    //console.log(record);

    closeMouldApi(record)
      .then((res) => {
        createMessage.success(res.message);
      })
      .catch((res) => {
        createMessage.error(res.message);
      })
      .finally(() => {
        tableRef.value.commitProxy('reload');
      });
  }

  function handleSuccess() {
    tableRef.value.commitProxy('reload');
  }

  function handleOk() {
    visible.value = false;
  }

  function openUserModal(record: Recordable) {
    orderModal[1].openModal(true, record);
  }

  /**
   * 导入excel
   * "费用名称","金额","供应商名称","真实物料编号(逗号隔开)","开始日期","退款条件类型","退款条件数量","经办人"
   */
  const arrHeader = [
    {
      key: 'mouldName',
      value: '*型号',
    },
    {
      key: 'materialName',
      value: '*物料名称',
    },
    {
      key: 'specification',
      value: '规格',
    },
    {
      key: 'supplierName',
      value: '*供应商名称',
    },
    {
      key: 'price',
      value: '*金额',
    },
    {
      key: 'remark',
      value: '备注',
    },
    {
      key: 'totalNum',
      value: '累计下单数量',
    },
    {
      key: 'startDate',
      value: '*开始日期(yyyy-MM-dd)',
    },
    {
      key: 'endDate',
      value: '结束日期(yyyy-MM-dd)',
    },
    {
      key: 'returnConditionType',
      value: '*退款条件类型',
    },
    {
      key: 'returnConditionNum',
      value: '*退款条件数量/金额',
    },
    {
      key: 'userName',
      value: '*经办人',
    },
  ];

  function getHeadArr() {
    let arr = [];
    arrHeader.forEach((r) => {
      arr.push(r.value);
    });
    return arr;
  }

  function changeSubmitArr(results) {
    let data = {
      list: [],
    };
    let list = [];
    results.forEach((r) => {
      let json = {};
      for (let key in r) {
        arrHeader.forEach((e) => {
          if (e.value == key) {
            json[e.key] = r[key];
          }
        });
      }
      data.list.push(json);
    });
    return data;
  }

  function excelSuccessFn(list) {
    let results = list[0].results;
    // console.log(results);
    //去除第一行文字提示 shift 删除第一行
    results.shift();
    let data = changeSubmitArr(results);
    // console.log(data);
    //
    // return;
    loading.value = true;
    importMsOrderExcelApi(data)
      .then((res) => {
        loading.value = false;

        if (res.code == 200) {
          if (res.data && res.data.length > 0) {
            // let msg="";
            // for(let i=0;i<res.data.length;i++){
            //   let row= res.data[i];
            //   msg+=`第${row.index}行 ${row.message}\n`
            // }
            msgList.value = res.data;
            visible.value = true;
          } else {
            createMessage.success('导入成功!');
            tableRef.value.commitProxy('reload');
          }
        } else {
          loading.value = false;

          createMessage.error(res.message);
        }
      })
      .catch((err) => {
        loading.value = false;
      });
  }
  function aoaToExcel() {
    // 保证data顺序与header一致
    // let arrHeader=[ "费用名称","金额","供应商名称","产品名称","备注","开始日期","退款条件类型","退款条件数量","经办人"];
    // aoaToSheetXlsx({
    //   data: [],
    //   header: arrHeader,
    //   filename: '费用导入模版.xlsx',
    // });

    window.open('http://220.161.77.66:10111/app_file/excel/费用导入模版.xlsx');
  }
</script>
<style lang="less">
  .isReturn_clazz {
    text-align: center;
    cursor: pointer;
  }
</style>
